package com.ybbase.framework.controller.system;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import com.ybbase.framework.base.model.TreeMessage;
import com.ybbase.framework.common.constant.CommonResultCode;
import com.ybbase.framework.common.util.BeanUtil;
import com.ybbase.framework.model.po.system.Dict;
import com.ybbase.framework.model.po.system.Role;
import com.ybbase.framework.model.po.system.RolePermission;
import com.ybbase.framework.model.vo.PermissionTreeVO;
import com.ybbase.framework.service.system.LogService;
import com.ybbase.framework.service.system.RoleService;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.RestController;
import com.ybbase.framework.base.controller.BaseController;
import com.ybbase.framework.service.system.PermissionService;
import com.ybbase.framework.model.po.system.Permission;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;
import java.util.ArrayList;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParams;
import com.ybbase.framework.base.model.ResponseBean;

import javax.servlet.http.HttpServletRequest;

/**
 * 系统菜单 前端控制器
 *
 * @author cg
 * @since 2019-11-26
 * 云平台2.0
 */
@RestController
@RequestMapping(value = "/permission", produces = {"application/json;charset=UTF-8"})
@Api("系统菜单")
public class PermissionController extends BaseController {

    private static final Logger LOGGER = LogManager.getLogger(PermissionController.class);

    @Autowired
    private PermissionService targetService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private LogService logService;


    /**
     * 获取权限列表
     *
     * @return ResponseBean
     * @author cg
     * @date 2019-12-01 21:20
     * @since cloud2.0
     */
    @GetMapping("/getMenuList")
    @ApiOperation(value = "获取权限列表", notes = "获取权限列表", response = ResponseBean.class)
    public ResponseBean getMenuList(HttpServletRequest request) {
        try {
            String userId = this.getUserId(getTokenString(request));
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统机构分页查询" + CommonResultCode.SUCCESS.getMsg(),
                    targetService.getPermissionTreeVOByUserId(Integer.parseInt(StringUtils.isNotEmpty(userId) ? userId : "0")));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统菜单分页查询异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统机构分页查询" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 角色获取权限列表
     *
     * @param request
     * @return
     */
    @GetMapping("/getPermissionMenuList")
    @ApiOperation(value = "角色获取权限列表", notes = "角色获取权限列表", response = ResponseBean.class)
    public ResponseBean getPermissionMenuList(String roleId) {
        TreeMessage treeMessage = new TreeMessage();
        try {
            treeMessage.setCode("200");
            treeMessage.setMessage("角色获取权限列表全部数据" + CommonResultCode.SUCCESS.getMsg());
            List<PermissionTreeVO> list = targetService.getPermissionTreeVOByRoleId(roleId);
            return new ResponseBean(treeMessage, list);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("角色获取权限列表全部数据异常：{}", e.getMessage());
            treeMessage.setCode("400");
            treeMessage.setMessage("角色获取权限列表全部数据" + CommonResultCode.SUCCESS.getMsg());
            return new ResponseBean(treeMessage, new ArrayList<>());
        }
    }

    /**
     * 角色获取权限列表
     *
     * @param request
     * @return
     */
    @GetMapping("/getPermissionMenuListCg")
    @ApiOperation(value = "角色获取权限列表", notes = "角色获取权限列表", response = ResponseBean.class)
    public ResponseBean getPermissionMenuListCg(Integer userId,String roleId,HttpServletRequest request) {
        TreeMessage treeMessage = new TreeMessage();
        try {
            treeMessage.setCode("200");
            treeMessage.setMessage("角色获取权限列表全部数据" + CommonResultCode.SUCCESS.getMsg());
            List<PermissionTreeVO> list = targetService.getPermissionTreeVOByRoleIdCg(userId,roleId);
            return new ResponseBean(treeMessage, list);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("角色获取权限列表全部数据异常：{}", e.getMessage());
            treeMessage.setCode("400");
            treeMessage.setMessage("角色获取权限列表全部数据" + CommonResultCode.SUCCESS.getMsg());
            return new ResponseBean(treeMessage, new ArrayList<>());
        }
    }

    /**
     * 系统菜单分页查询
     *
     * @param pageIndex 页数
     * @param step      每页数量
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @GetMapping("/list")
    @ApiOperation(value = "系统菜单分页查询", notes = "系统菜单分页查询", response = ResponseBean.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "rows", value = "每页行数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "permission", value = "系统菜单", dataType = "Permission对象")
    })
    public ResponseBean findListByPage(@RequestParam(name = "current", defaultValue = "1") int pageIndex,
                                       @RequestParam(name = "size", defaultValue = "20") int step, Permission permission) {
        try {
            Page<Permission> page = new Page(pageIndex, step);
            if (permission.getRouterName() != null) {
                QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(Permission::getRouterName, permission.getRouterName());
                targetService.page(page, queryWrapper);
            } else {
                Wrapper<Permission> wrapper = new QueryWrapper<Permission>();
                targetService.page(page, wrapper);
            }
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统菜单分页查询" + CommonResultCode.SUCCESS.getMsg(), page);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统菜单分页查询异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统菜单分页查询" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 根据用户编码获取所有权限列表
     * @param userId 用户编码
     * @return
     * @author cg
     * @date 2020-01-20 16:44
     * @since cloud2.0
     */
    @GetMapping("/getAllByUserId")
    @ApiOperation(value = "根据用户编码获取所有权限列表", notes = "根据用户编码获取所有权限列表")
    public ResponseBean getAllByUserId(String userId){
        try{
            List<Permission> models = new ArrayList<>();
            if (StringUtils.isNotEmpty(userId)){
                List<Role> roleList = roleService.getRoleListByUserId(Integer.parseInt(userId));
                String roleIds = "";
                if (roleList!=null&&roleList.size()>0){
                    for(Role role:roleList){
                        if(roleIds==""){
                            roleIds = role.getId()+"";
                        }else {
                            roleIds = roleIds +","+ role.getId();
                        }
                    }
                    models = targetService.getPermissionButtonInRoleIds(roleIds);
                }
            }
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统菜单分页查询" + CommonResultCode.SUCCESS.getMsg(),models);
        }catch (Exception e){
            e.printStackTrace();
            LOGGER.error("根据用户编码获取所有权限列表异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统菜单分页查询" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统菜单获取全部数据
     *
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @GetMapping("/all")
    @ApiOperation(value = "系统菜单获取全部数据", notes = "系统菜单获取全部数据")
    public ResponseBean findAll() {
        try {
            List<Permission> models = targetService.list();
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统菜单获取全部数据" + CommonResultCode.SUCCESS.getMsg(),
                    targetService.findSortPermission(models));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统菜单获取全部数据异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统菜单获取全部数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统菜单根据ID查找数据
     *
     * @param id 唯一编码
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @GetMapping("/find")
    @ApiOperation(value = "系统菜单根据ID查找数据", notes = "系统菜单根据ID查找数据")
    @ApiImplicitParam(required = true, name = "id", value = "唯一编码", dataType = "Long")
    public ResponseBean find(@RequestParam("id") Long id) {
        try {
            Permission permission = targetService.getById(id);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统菜单根据ID查找数据" + CommonResultCode.SUCCESS.getMsg(), permission);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统菜单根据ID查找数据异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统菜单根据ID查找数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统菜单保存数据
     *
     * @param permission 系统菜单
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @PostMapping("/save")
    @ApiOperation(value = "系统菜单保存数据", notes = "系统菜单保存数据")
    @ApiImplicitParam(required = true, name = "permission", value = "系统菜单", dataType = "Permission对象")
    public ResponseBean save(HttpServletRequest request) {
        try {
            BeanUtil beanUtil = new BeanUtil();
            Permission permission = (Permission) beanUtil.mapToObject(request.getParameterMap(), Permission.class);
            targetService.savePermissionMenu(permission);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统菜单保存数据" + CommonResultCode.SUCCESS.getMsg(), permission);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统菜单保存数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统菜单保存数据" + CommonResultCode.FAIL.getMsg());

        }
    }

    /**
     * 系统菜单更新数据
     *
     * @param permission 系统菜单
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @PutMapping("/update")
    @ApiOperation(value = "系统菜单更新数据", notes = "系统菜单更新数据")
    @ApiImplicitParam(required = true, name = "permission", value = "系统菜单", dataType = "Permission对象")
    public ResponseBean update(@RequestBody Permission permission) {
        try {
            targetService.updateById(permission);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统菜单更新数据" + CommonResultCode.SUCCESS.getMsg(), permission);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统菜单更新数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统菜单更新数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统菜单删除数据
     *
     * @param ids 批量删除数据
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @DeleteMapping("/del")
    @ApiOperation(value = "系统菜单删除数据", notes = "系统菜单删除数据")
    @ApiImplicitParam(required = true, name = "ids", value = "批量删除数据", dataType = "List<Long>")
    public ResponseBean del(@RequestParam("ids") List<Integer> ids) {
        try {
            if (ids != null && !ids.isEmpty()) {
                for (Integer id : ids) {
                    QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(RolePermission::getPerId, id);
                    List<RolePermission> list = targetService.getRolePermissionListByPerId(queryWrapper);
                    if (list != null && !list.isEmpty()) {
                        return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统菜单删除数据" + CommonResultCode.FAIL.getMsg());
                    }
                }
            }
            targetService.removeByIds(ids);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统菜单删除数据" + CommonResultCode.SUCCESS.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统菜单删除数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统菜单删除数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 根据id删除
     *
     * @param ids
     * @return
     */
    @GetMapping("/delete")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    @ApiImplicitParam(required = true, name = "ids", value = "批量删除数据", dataType = "List<Long>")
    public ResponseBean delete(@RequestParam("id") Integer id) {
        try {
            targetService.removeById(id);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统菜单删除数据" + CommonResultCode.SUCCESS.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统菜单删除数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统菜单删除数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 获取菜单权限二级树
     *
     * @return
     */
    @GetMapping("/getPerTree")
    @ApiOperation(value = "获取菜单权限二级树", notes = "获取菜单权限二级树")
    public ResponseBean getPerTree() {
        try {
            List<Permission> list = targetService.getPerTree();
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "获取权限树" + CommonResultCode.SUCCESS.getMsg(), targetService.findSortPermission(list));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("权限树获取异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "权限树" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 根据ParentId查子菜单项目
     *
     * @param pageIndex
     * @param step
     * @param parentId
     * @return
     */
    @GetMapping("/findByParentId")
    @ApiOperation(value = "根据ParentId查子菜单项目分页数据", notes = "根据ParentId查子菜单项目分页数据", response = ResponseBean.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "rows", value = "每页行数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "permission", value = "权限菜单", dataType = "Permission对象")
    })
    public ResponseBean findByParentId(@RequestParam(name = "current", defaultValue = "1") int pageIndex,
                                       @RequestParam(name = "size", defaultValue = "20") int step, Integer parentId) {
        try {
            QueryWrapper<Permission> queryWrapper = new QueryWrapper<Permission>();
            Page<Permission> page = new Page<>(pageIndex, step);
            targetService.findByParentId(page, queryWrapper, parentId);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "根据ParentId查子菜单项目分页数据" + CommonResultCode.SUCCESS.getMsg(), page);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("根据ParentId查子菜单项目分页数据异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "根据ParentId查子菜单项目分页数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 保存权限和数据范围的对应关系
     * @param
     * @return
     * @author cg
     * @date 2020-03-26 09:55
     * @since cloud2.0
    */
    @PostMapping("/saveUserPerData")
    @ApiOperation(value = "保存权限和数据范围的对应关系", notes = "保存权限和数据范围的对应关系", response = ResponseBean.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "perId", value = "权限编码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "dataScope", value = "数据权限编码", required = true, dataType = "Integer")
    })
    public ResponseBean saveUserPerData(@RequestParam(name = "userId")Integer userId,
                                        @RequestParam(name = "perId")Integer perId,
                                        @RequestParam(name = "dataScope") Integer dataScope){
        try {
            targetService.saveUserPermission(perId,userId,dataScope);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "保存权限和数据范围的对应关系" + CommonResultCode.SUCCESS.getMsg(), perId+"_"+dataScope);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("保存权限和数据范围的对应关系：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "保存权限和数据范围的对应关系" + CommonResultCode.FAIL.getMsg());
        }

    }
}
